package id.co.gomobile.assessment

import org.codehaus.groovy.grails.plugins.springsecurity.Secured;

class UserController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def authenticateService
	def registrationService
	
	@Secured(["IS_AUTHENTICATED_FULLY"])
    def index = {
        redirect(action: "profile", params: params)
    }

	@Secured(["ROLE_ADMIN"])
    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [userInstanceList: User.list(params), userInstanceTotal: User.count()]
    }

	@Secured(["ROLE_ADMIN"])
    def create = {
        def userInstance = new User([roles: Role.findByName('ROLE_USER')])
        userInstance.properties = params
        return [userInstance: userInstance]
    }

	@Secured(["ROLE_ADMIN"])
    def save = {
        def userInstance = new User(params)
		def password = registrationService.createRandomPassword()
		userInstance.password = authenticateService.encodePassword(password)
        if (!userInstance.hasErrors() && userInstance.save(flush: true)) {
			Role.findByName("ROLE_USER").addToUsers(userInstance)
			if(params.administrator) {
				Role.findByName("ROLE_ADMIN").addToUsers(userInstance)
			} else {
				Role.findByName("ROLE_ADMIN").removeFromUsers(userInstance)
			}
			
			_sendRegistrationEmail(userInstance, password)
			
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), userInstance.username])}"
            redirect(action: "show", id: userInstance.id)
        }
        else {
            render(view: "create", model: [userInstance: userInstance])
        }
    }

	@Secured(["ROLE_ADMIN"])
    def show = {
        def userInstance = User.get(params.id)
        if (!userInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
            redirect(action: "list")
        }
        else {
			// default sort order
			if(!params.sort) {
				params.sort = "endTime"
				params.order = "desc"
			}
			
			def assignmentInstanceList = Assignment.findAllByUser(userInstance, params)
            [userInstance: userInstance, assignmentInstanceList: assignmentInstanceList]
        }
    }

	@Secured(["ROLE_ADMIN"])
    def edit = {
        def userInstance = User.get(params.id)
        if (!userInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [userInstance: userInstance]
        }
    }

	@Secured(["ROLE_ADMIN"])
    def update = {
        def userInstance = User.get(params.id)
        if (userInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (userInstance.version > version) {
                    userInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'user.label', default: 'User')] as Object[], "Another user has updated this User while you were editing")
                    render(view: "edit", model: [userInstance: userInstance])
                    return
                }
            }
            userInstance.properties = params
			if(params.pass) {
				userInstance.password = authenticateService.encodePassword(params.pass)
			}
            if (!userInstance.hasErrors() && userInstance.save(flush: true)) {
				if(params.administrator) {
					Role.findByName("ROLE_ADMIN").addToUsers(userInstance)
				} else {
					Role.findByName("ROLE_ADMIN").removeFromUsers(userInstance)
				}
				flash.message = "${message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), userInstance.username])}"
                redirect(action: "show", id: userInstance.id)
            }
            else {
                render(view: "edit", model: [userInstance: userInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
            redirect(action: "list")
        }
    }

	@Secured(["ROLE_ADMIN"])
    def delete = {
        def userInstance = User.get(params.id)
        if (userInstance) {
            try {
                userInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'user.label', default: 'User'), userInstance.username])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'user.label', default: 'User'), userInstance.username])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
            redirect(action: "list")
        }
    }
	
	
	
	// authenticated user only
	@Secured(["IS_AUTHENTICATED_FULLY"])
    def profile = {
		def username = request.remoteUser
        def userInstance = User.findByUsername(username)
        if (!userInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.username])}"
            redirect(action: "list")
        }
        else {
            [userInstance: userInstance]
        }
    }
	
	@Secured(["IS_AUTHENTICATED_FULLY"])
	def editProfile = {
		def username = request.remoteUser
		def userInstance = User.findByUsername(username)
		if (!userInstance) {
			flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.username])}"
			redirect(action: "list")
		}
		else {
			[userInstance: userInstance]
		}
	}

	@Secured(["IS_AUTHENTICATED_FULLY"])
	def updateProfile = {
		def username = request.remoteUser
		def userInstance = User.findByUsername(username)
		if (userInstance) {
			if (params.version) {
				def version = params.version.toLong()
				if (userInstance.version > version) {
					userInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'user.label', default: 'User')] as Object[], "Another user has updated this User while you were editing")
					render(view: "editProfile", model: [userInstance: userInstance])
					return
				}
			}
			userInstance.properties = params
			if(params.pass) {
				userInstance.password = authenticateService.encodePassword(params.pass)
			}
			if (!userInstance.hasErrors() && userInstance.save(flush: true)) {
				flash.message = "${message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), userInstance.username])}"
				redirect(action: "profile")
			}
			else {
				render(view: "editProfile", model: [userInstance: userInstance])
			}
		}
		else {
			flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.username])}"
			redirect(uri: "/")
		}
	}
	
	@Secured(["IS_AUTHENTICATED_FULLY"])
	def changePassword = {
		
	}
	
	def _sendRegistrationEmail = { userInstance, password ->
		sendMail {
		 	to userInstance.email
		 	subject "${message(code: 'email.registered.subject')}"
		 	body (view: "/shared/emails/registered", model: [userInstance: userInstance, password: password])
		}
	}
	
}
